package com.haochang.chunkvod.app.database.order;

import java.sql.SQLException;

import com.haochang.base.VodApplication;
import com.haochang.chunkvod.app.config.DatabaseConfig;
import com.haochang.chunkvod.model.BaseInfo;
import com.haochang.chunkvod.model.cash.PrintInfo;
import com.haochang.chunkvod.model.order.GoodsInfo;
import com.haochang.chunkvod.model.order.PartInfo;
import com.haochang.chunkvod.model.order.RoomInfo;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

/**
 *@author qintao
 *created at 2016/6/15 17:01
 * 点餐数据Helper
 */

public class OrderOpenHelper extends OrmLiteSqliteOpenHelper
{

	private static OrderOpenHelper helper;

	public static OrderOpenHelper getHelper()
	{
		return getHelper(VodApplication.appContext);
	}

	public static OrderOpenHelper getHelper(Context context)
	{
		if (helper == null || !helper.isOpen())
			helper = new OrderOpenHelper();
		return helper;
	}

	public OrderOpenHelper()
	{
		//避免内存泄露,直接使用Application对象
		super(VodApplication.appContext, DatabaseConfig.DatabaseEnum.ORDER.getDatabaseName(), null, DatabaseConfig.DatabaseEnum.ORDER.getDatabaseVersion());
	}

	@Override
	public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource)
	{
		for (Class<?> classes : mDbClasses)
		{
			try
			{
				TableUtils.createTable(connectionSource, classes);
				DaoManager.createDao(connectionSource, classes);
			} catch (SQLException e)
			{
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion)
	{
		for (Class<?> classes : mDbClasses)
		{
			try
			{
				TableUtils.dropTable(connectionSource, classes, true);
			} catch (SQLException e)
			{
				e.printStackTrace();
			}
		}
		onCreate(db, connectionSource);
	}

	private static Class<?>[] mDbClasses = { PartInfo.class, RoomInfo.class, GoodsInfo.class, PrintInfo.class, BaseInfo.class };
}
